import React, { useState, useEffect } from 'react';
import { Modal, Form, message, Button, Upload, Input } from 'antd';
import styles from "./User.less";

const FormItem = Form.Item;

const UserModal = (props) => {

    const {
        themeColor, userModalVisible, addOrUpdateUser, closeUserModal, userRecord, documentLoading
    } = props;

    let [userPhoto, setUserPhoto] = useState(null);
    userPhoto = userPhoto ? userPhoto : userRecord.photo;

    const [form] = Form.useForm();
    const { getFieldsValue, validateFields, setFieldsValue, resetFields } = form;

    useEffect(() => {
        setFieldsValue(userRecord);
    }, [userRecord]);

    const onOk = () => {
        validateFields().then(values => {
            values.photo = userPhoto;
            addOrUpdateUser(values);
            setUserPhoto(null);
        }).catch(error => {
            const errors = error.errorFields;
            for (let i = 0; i < errors.length; i++) {
                console.log("UserModal Error => " + errors[i].name[0] + " ===>>> " + errors[i].errors[0]);
            }
        });
    }

    const generateFooter = () => <div>
        <Button size="default" style={{ background: themeColor }} loading={documentLoading} onClick={() => onOk()}>确定</Button>
        <Button size="default" style={{ marginLeft: 20 }} onClick={() => closeUserModal()}>取消</Button>
    </div>

    const formItemLayout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 }
    }

    const uploadProps = {
        name: "PictureToolBar",
        listType: "picture-card",
        className: "avatar-uploader",
        showUploadList: false,
        beforeUpload: (file) => {
            const fileNames = file.name.split(".");
            const fileType = fileNames[fileNames.length - 1];
            if (["jpg", "png", "gif"].indexOf(fileType) < 0) {
                message.error('只能上传jpg、png、gif格式！');
                return false;
            }
            if (file.size / 1024 / 1024 > 2) {
                message.error('上传大小限制为2M！');
                return false;
            }

            const fileReader = new FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onload = function (event) {
                let base64 = event.target.result;
                setUserPhoto(base64);
            }
        },
    }

    const uploadButton = (
        <div>
            <i className={"ri-user-line"} style={{ fontSize: "24px" }} />
            <div style={{ marginTop: 0 }}>上传头像</div>
        </div>
    )

    return (
        <div>
            <Modal
                title = { userRecord ? "编辑用户" : "新增用户"}
                width={600}
                height={400}
                clearOnDestroy={true}
                open = {userModalVisible}
                onCancel = {closeUserModal}
                footer = {generateFooter()}
                closable = {{ 'aria-label': 'Custom Close Button' }}
            >
                <div style={{ padding: "15px 0px 50px 0px", lineHeight: 3 }}>
                    <Form form={form} labelAlign="left" { ...formItemLayout }>
                        <FormItem label="用户名" name="user_name">
                            <Input placeholder={"请输入用户名"} style={{ width: '100%' }} />
                        </FormItem>
                        <FormItem label="密码" name="password">
                            <Input placeholder={"请输入密码"} style={{ width: '100%' }} />
                        </FormItem>
                        <FormItem label="手机号码" name="phone_number">
                            <Input placeholder={"请输入手机号码"} style={{ width: '100%' }} />
                        </FormItem>
                        <FormItem label="邮箱" name="email">
                            <Input placeholder={"请输入邮箱"} style={{ width: '100%' }} />
                        </FormItem>
                        <FormItem label="照片头像" name="photo">
                            <Upload {...uploadProps} className={styles.uploadDiv}>
                                {
                                    userPhoto ? <img src={userPhoto} alt="avatar" style={{ height: 86 }} /> : uploadButton
                                }
                            </Upload>
                        </FormItem>
                        <FormItem label="个人简介" name="resume">
                            <Input.TextArea placeholder={"请输入个人简介"} style={{ width: '100%', height: 120 }} />
                        </FormItem>
                    </Form>
                </div>
            </Modal>
        </div>
    );
};

export default UserModal;
